<template>
	<!-- 
        签名组件
        LYH LZy
        横屏组件
     -->
	<view class="signa">
		<view class="btn-bar">
			<view class="btn cancel-btn" @click="clear">
				重写
			</view>

			<view class="btn save-btn" @click="save">
				保存
			</view>

			<view class="btn cancel-bth" @click="close">
				关闭
			</view>
		</view>
		<canvas class="canvas" disable-scroll="true" :style="{'width':width,'height':height}" canvas-id="designature"
			@touchstart="starts" @touchmove="moves" @touchend="end"></canvas>
		<!--用于旋转图片的canvas容器-->
		<!-- <canvas style="position: absolute; " :style="{ width: cavWidth, height: cavWidth1 }"
			canvas-id="handWriting2"></canvas> -->
	</view>
</template>

<script>
	export default {
		name: "qianming",
		data() {
			return {
				dom: null,
				line: [],
				radius: 0,
				width: '0px',
				height: '0px',
				drawed: false, // 标记是否已书写
				lineSize: 4, // 画笔大小

				cavWidth: 2000,
				cavWidth1: 2000,
			}
		},
		onLoad() {

		},
		computed: {

		},
		created() {
			uni.getSystemInfo({
				success: (res) => {
					this.width = res.windowWidth - 60 + 'px';
					this.height = res.windowHeight - 30 + 'px';
				}
			});
			this.dom = uni.createCanvasContext('designature', this);
		},
		onShow() {
			// 进入页面清空页面内容，便于多人签名。 add by LZy
			this.clear();
		},
		methods: {
			end(e) {

			},
			distance(a, b) {
				let x = b.x - a.x;
				let y = b.y - a.y;
				return Math.sqrt(x * x + y * y);
			},
			// 开始
			starts(e) {
				this.line.push({
					points: [{
						time: new Date().getTime(),
						x: e.touches[0].x,
						y: e.touches[0].y,
						dis: 0
					}]
				})
				let currentPoint = {
					x: e.touches[0].x,
					y: e.touches[0].y
				}
				this.currentPoint = currentPoint
				this.drawer(this.line[this.line.length - 1])
			},
			// 滑动
			moves(e) {
				let point = {
					x: e.touches[0].x,
					y: e.touches[0].y
				}
				this.lastPoint = this.currentPoint,
					this.currentPoint = point
				this.line[this.line.length - 1].points.push({
					time: new Date().getTime(),
					x: e.touches[0].x,
					y: e.touches[0].y,
					dis: this.distance(this.currentPoint, this.lastPoint)
				})
				this.drawer(this.line[this.line.length - 1])
			},
			// 书写
			drawer(item) {
				this.drawed = true; // 标记已书写
				let x1, x2, y1, y2, len, radius, r, cx, cy, t = 0.5,
					x, y;
				var time = 0;
				if (item.points.length > 2) {
					let lines = item.points[item.points.length - 3];
					let line = item.points[item.points.length - 2];
					let end = item.points[item.points.length - 1];
					x = line.x;
					y = line.y;
					x1 = lines.x;
					y1 = lines.y;
					x2 = end.x;
					y2 = end.y;
					var dis = 0;
					time = (line.time - lines.time) + (end.time - line.time)
					dis = line.dis + lines.dis + end.dis;
					var dom = this.dom;
					var or = Math.min(time / dis * this.linePressure + this.lineMin, this.lineMax);
					cx = (x - (Math.pow(1 - t, 2) * x1) - Math.pow(t, 2) * x2) / (2 * t * (1 - t))
					cy = (y - (Math.pow(1 - t, 2) * y1) - Math.pow(t, 2) * y2) / (2 * t * (1 - t))
					dom.setLineCap('round')
					dom.beginPath();
					dom.setStrokeStyle('black')
					dom.setLineWidth(this.lineSize)
					dom.moveTo(x1, y1);
					dom.quadraticCurveTo(cx, cy, x2, y2);
					dom.stroke();
					dom.draw(true)
				}
			},
			// 清除
			clear() {
				this.dom.clearRect(0, 0, 1000, 1000)
				this.dom.draw()
				
				// this.dom.clearRect(0, 0, this.width, this.height)
				// this.dom.draw()
			},
			//关闭
			close(e) {
				this.$emit('close', false);
			},
			// 保存图片
			save() {
				if (!this.drawed) {
					vk.alert('尚未签名，无法保存。')
					return false;
				}
				var t = this;
				// uni.canvasToTempFilePath({
				// 	canvasId: 'designature',
				// 	fileType: 'png',
				// 	quality: 1, //图片质量
				// 	success: function(res) {
				// 		// t.$emit('getImg',res.tempFilePath)
				// 		// uni.navigateBack({
				// 		//     delta:1
				// 		// })
				// 		// console.log('canvasToTempFilePath', res)

				// 		// LZy 上传到阿里云空间，返回图片访问地址fileID
				// 		let arr = res.tempFilePath.split("/");
				// 		let cloudPath = arr[arr.length - 1]

				// 		uniCloud.uploadFile({
				// 			filePath: res.tempFilePath,
				// 			cloudPath,
				// 			success: (res) => {
				// 				console.log('上传云空间success', res)
				// 				t.$emit('getImg', res.fileID)
				// 			},
				// 			fail: (err) => {
				// 				console.log('上传云空间fail', err)
				// 			}
				// 		})
				// 	},
				// 	fail(e) {
				// 		console.log(e)
				// 	}
				// }, this)

				// 旋转 by LZy
				var that = this;
				uni.canvasToTempFilePath({
					canvasId: 'designature',
					fileType: 'png',
					quality: 1, //图片质量
					success: function(res) {
						// console.log('原图上传res', res)
						uni.getImageInfo({
							// 获取图片的信息
							src: res.tempFilePath,
							success: (res1) => {
								// console.log('获取图片的信息res1', res1)
								// 将canvas1的内容复制到canvas2中
								// let canvasContext = uni.createCanvasContext('handWriting2', that)
								// let canvasContext = this.dom
								
								let rate = res1.height / res1.width
								let width = 300 / rate
								let height = 300
								that.cavWidth = 300 / rate
								that.cavWidth1 = 300
								that.width = 300 / rate
								that.height = 300
								
								let canvasContext = uni.createCanvasContext('designature', that)
								
								canvasContext.setLineCap('round')
								canvasContext.setStrokeStyle('black')
								canvasContext.setLineWidth(that.lineSize)
								
								canvasContext.translate(height / 2, width / 2)
								canvasContext.rotate((270 * Math.PI) / 180)
								canvasContext.drawImage(res.tempFilePath, -width / 2, -height / 2,
									width, height)
								
								setTimeout(()=>{
									// console.log('setTimeout in')
									canvasContext.draw(false, () => {
										// console.log('二次draw')
										// 将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中
										uni.canvasToTempFilePath({
											// 把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功。
											canvasId: 'designature',
											fileType: 'png',
											quality: 1, //图片质量
											x: 0,
											y: 0,
											width: height,
											height: height / 2,
											success(res2) {
												// 调用uni.uploadFile上传图片即可
												// console.log('旋转上传res', res2)
												// LZy 上传到阿里云空间，返回图片访问地址fileID
												
												// let arr = res2.tempFilePath.split("/");
												// let cloudPath = arr[arr.length - 1]
												
												let cloudPath = 'sign_' + new Date().getTime() + '.png';
												
												// console.log('cloudPath', cloudPath)
									
												uniCloud.uploadFile({
													filePath: res2.tempFilePath,
													cloudPath,  // 云端文件名
													success: (res3) => {
														// console.log('上传云空间success', res3)
														that.$emit('getImg', res3.fileID)
													},
													fail: (err) => {
														console.log('上传云空间fail', err)
													}
												})
											}
										}, that)
									})
								
								}, 1000)
								
								// setTimeout(()=>{
								// 	console.log('setTimeout in')
									
								// 	canvasContext.draw(false, () => {
								// 		console.log('handWriting2 draw in')
										
								// 		// 将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中
								// 		uni.canvasToTempFilePath({
								// 			// 把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功。
								// 			canvasId: 'handWriting2',
								// 			fileType: 'png',
								// 			quality: 1, //图片质量
								// 			success(res2) {
								// 				// 调用uni.uploadFile上传图片即可
								// 				console.log('旋转上传res', res2)
								// 				// LZy 上传到阿里云空间，返回图片访问地址fileID
												
								// 				// let arr = res2.tempFilePath.split("/");
								// 				// let cloudPath = arr[arr.length - 1]
												
								// 				let cloudPath = 'sign_' + new Date().getTime() + '.png';
												
								// 				console.log('cloudPath', cloudPath)
									
								// 				uniCloud.uploadFile({
								// 					filePath: res2.tempFilePath,
								// 					cloudPath,  // 云端文件名
								// 					success: (res3) => {
								// 						console.log('上传云空间success', res3)
								// 						that.$emit('getImg', res3.fileID)
								// 					},
								// 					fail: (err) => {
								// 						console.log('上传云空间fail', err)
								// 					}
								// 				})
								// 			}
								// 		})
								// 	})
								// }, 5000)
								// canvasContext.fill()
								// setTimeout(()=>{
								// 	console.log('setTimeout in')
								// 	// canvasContext.draw(true)
								// 	canvasContext.draw(false, ()=>{
								// 		console.log('handWriting2 draw in')
								// 	})
								// }, 1000)
								
								// canvasContext.draw(false, ()=>{
								// 	console.log('handWriting2 draw in')
								// })
								// canvasContext.draw(false, () => {
								// 	console.log('handWriting2 draw in')
									
								// 	// 将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中
								// 	uni.canvasToTempFilePath({
								// 		// 把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功。
								// 		canvasId: 'handWriting2',
								// 		fileType: 'png',
								// 		quality: 1, //图片质量
								// 		success(res2) {
								// 			// 调用uni.uploadFile上传图片即可
								// 			console.log('旋转上传res', res2)
								// 			// LZy 上传到阿里云空间，返回图片访问地址fileID
											
								// 			// let arr = res2.tempFilePath.split("/");
								// 			// let cloudPath = arr[arr.length - 1]
											
								// 			let cloudPath = 'sign_' + new Date().getTime() + '.png';
											
								// 			console.log('cloudPath', cloudPath)
								
								// 			uniCloud.uploadFile({
								// 				filePath: res2.tempFilePath,
								// 				cloudPath,  // 云端文件名
								// 				success: (res3) => {
								// 					console.log('上传云空间success', res3)
								// 					that.$emit('getImg', res3.fileID)
								// 				},
								// 				fail: (err) => {
								// 					console.log('上传云空间fail', err)
								// 				}
								// 			})
								// 		}
								// 	})
								// })
								
							},
						})
					},
					fail(e) {
						console.log(e)
					}
				}, this)
			}
		}
	}
</script>

<style scoped lang="scss">
	.signa {
		position: relative;
		overflow: hidden;
		background-color: #f1efef;
		height: 100vh;
		width: 100vw;
		z-index: 10074;

		.canvas {
			background-color: #FFFFFF;
			position: absolute;
			z-index: 10075;
			left: 50px;
			top: 6px;
			border: 1px solid #d6d6d6;
		}

		.btn-bar {
			position: fixed;
			height: 100vh;
			background-color: #007AFF;
			font-size: 32rpx;

			.btn {
				position: absolute;
				left: -5vh;
				width: 20vh;
				height: 65rpx;
				line-height: 65rpx;
				text-align: center;
				border-radius: 3px;
				transform: rotate(90deg);
			}

			.cancel-btn {
				top: 15vh;
				border: 1rpx solid #a9a1a1;
				color: #666;
			}

			.save-btn {
				top: 47vh;
				background: #007AFF;
				color: #fff;
				border: 1rpx solid #007AFF;
			}

			.cancel-bth {
				top: 80vh;
				background: #de7f7f;
				color: #fff;
				border: 1rpx solid #de7f7f;
			}
		}
	}
</style>